package xframe.util.mail;

import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;


public class GMailSender {

 
    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub
        String host = "smtp.gmail.com";//smtp 서버
        String subject = "자자 파일 갑니다.ㅎ";
        String from = "akami.java@gmail.com"; //보내는 메일
        String fromName = "강백석";
        //String to = "akami@ez-i.co.kr";
        String to = "akami.kang@samsung.com";
        //String content = "쏭!! 이거 문자 보여용???";

        try{
            // 프로퍼티 값 인스턴스 생성과 기본세션(SMTP 서버 호스트 지정)
            Properties props = new Properties();
            
            // G-Mail SMTP 사용시
            props.put("mail.smtp.starttls.enable","true");
            props.put("mail.transport.protocol", "smtp");
            props.put("mail.smtp.host", host);
            props.setProperty("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.port", "465");
            // props.put("mail.smtp.user", from);
            props.put("mail.smtp.auth", "true");
            
            MyAuthenticator auth = new MyAuthenticator("akami.mail@gmail.com", "ollist1234");
            
            Session mailSession = Session.getDefaultInstance(props, auth);
            System.out.println("[메일서버 접속]");
            
            Message msg = new MimeMessage(mailSession);
            msg.addHeader("Content-Transfer-Encoding","euc-kr");

            msg.setFrom(new InternetAddress(from, MimeUtility.encodeText(fromName,"UTF-8","B")));//보내는 사람 설정
           // mbp1.setContent(MimeUtility.encodeText(content,"euc-kr","B"),"text/html;charset=euc-kr");
            InternetAddress[] address = {new InternetAddress(to)};
            
            msg.setRecipients(Message.RecipientType.TO, address);//받는 사람설정
            
            msg.setSubject(subject);// 제목 설정
            msg.setSentDate(new java.util.Date());// 보내는 날짜 설정
            //msg.setContent(content,"text/html;charset=euc-kr"); // 내용 설정 (HTML 형식)
            
                   	// create the Multipart and its parts to it
        	String [] filePath = {"D:\\shared\\개발문서1차 제출 문서\\1.검수확인서\\검수확인서.doc","D:\\temp\\WebRoot\\frameset.html"};
        	Multipart mp = new MimeMultipart();
        	
        	sendMail(mp, "<script>alert(1)</script><strong>보</strong>이나", filePath);

        	
        	// add the Multipart to the message
        	msg.setContent(mp);
        	System.out.println("[첨부파일을 메일로 첨부완료]");
        	//System.out.println("[메일 전송 중]:"+fds.getFile().size());
            Transport.send(msg); // 메일 보내기
            
            System.out.println("메일 발송을 완료하였습니다.");
        } catch ( MessagingException ex ) {
            System.out.println("mail send error : " + ex.getMessage());
        } catch ( Exception e ) {
            System.out.println("error : " + e.getMessage());
        }
        
    }
    
    public static Multipart sendMail(Multipart mp, String Contents, String[] filePath) throws MessagingException, UnsupportedEncodingException{
        BodyPart bodyPart = new MimeBodyPart();
        bodyPart.setText(Contents);
        mp.addBodyPart(bodyPart);
        MimeBodyPart mimeBodyPart ;
        if(filePath != null && filePath.length > 0){
        	for(int i = 0 ; i < filePath.length ; i++){
        	mimeBodyPart = new MimeBodyPart();
	    	//mimeBodyPart.setText("첨부파일"+i);
	    	// attach the file to the message
	    	FileDataSource fds = new FileDataSource(filePath[i]);
	    	mimeBodyPart.setDataHandler(new DataHandler(fds));
	    	String msgSubj = new String(fds.getName().getBytes("KSC5601"), "ISO-8859-1");
	    	mimeBodyPart.setFileName(msgSubj);
	    	mp.addBodyPart(mimeBodyPart);
        	}
        }
        return mp;
    }

}

 


